<?php


namespace App\Http\Controllers\applets\service;


use App\Http\Controllers\admin\service\AccountCenterService;
use App\Http\Controllers\applets\model\AdminModel;
use App\Http\Controllers\applets\model\AdminSnModel;
use App\Http\Controllers\applets\model\BatchModel;
use App\Http\Controllers\applets\model\BindSnModel;
use App\Http\Controllers\applets\model\ParentSnModel;
use App\Http\Controllers\applets\model\SendTeacherModel;
use App\Http\Controllers\applets\model\SettingModel;
use App\Http\Controllers\applets\model\TeacherSnModel;
use App\Http\Controllers\utils\LogUtil;
use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;

class ParentSnService
{
    /**
     * 申请授权
     * @param $param
     * @return false|string
     */
    public static function applyEmpower($param){
        $batch = BatchModel::queryFirst(['rand_code'=>$param['randCode']],['id','admin_id']);
        if(!$batch){
            return ToolUtil::returnJson(301,'邀请码不正确');
        }
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']!=4){
            return ToolUtil::returnJson(302,'不是家长账号，不能发起授权');
        }
        $param['remark'] = '申请授权';
        $parent = ParentSnModel::queryWhereFirst(['a.value'=>$param['snCode']],['p.id as id','a.id as aId']);
        if(!$parent){
            return ToolUtil::returnJson(303,'不存在该设备');
        }

        if(DB::table('t_teacher_sn')->where('admin_sn_id',$parent['aId'])->value('id')){
            return ToolUtil::returnJson(301,'已经授权,不能重复授权');
        }
        DB::beginTransaction();
        $int = ParentSnModel::edit(['id'=>$parent['id']],['teacher_id'=>$batch['admin_id'],'update_time'=>time()]);
        $data = [
            'admin_sn_id'=>$parent['aId'],
            'batch_id'=>$batch['id'],
            'admin_id'=>$batch['admin_id']
        ];
        $int2 = TeacherSnModel::add($data);

        if($int>0 && $int2>0){
            $param['details'] = ToolUtil::handleSuccessOrError($param);
            LogUtil::addAdminLog($param);
            DB::table('t_app_inside')->where(['sn'=>$param['snCode']])->delete();
            DB::commit();
            $param['contentType'] = 45;
            $param['status'] = 1;
            $param['batch'] = array($param['snCode']);
            $param['type'] = 2;
            $param['statusType'] = '设备授权';
            $jPush = LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'授权成功');
            }            
            return ToolUtil::returnJson(200,'授权成功，推送失败');
        }
        return ToolUtil::returnJson(300,'发起授权失败');
    }

    /**
     * 解除授权
     * @param $param
     * @return false|string
     */
    public static function relieveEmpower($param){
        $parent = ParentSnModel::queryFirst(['id'=>$param['id']],['admin_sn_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(302,'该设备没有进行授权');
        }
        $adminSn = AdminSnModel::queryFirst(['id'=>$parent['admin_sn_id']],['value']);
        $param['remark'] = '解除授权';
        if($adminSn){
            DB::beginTransaction();
            $par = ParentSnModel::edit(['admin_sn_id'=>$parent['admin_sn_id']],['teacher_id'=>0,'update_time'=>time()]);
            $tea = TeacherSnModel::delete(['admin_sn_id'=>$parent['admin_sn_id']]);
            if($par>0 && $tea>0){
                
                $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'success','sn'=>$adminSn['value']]);
                LogUtil::addAdminLog($param);
                DB::commit();
                $param['contentType'] = 45;
                $param['status'] = 1;
                $param['batch'] = array($adminSn['value']);
                $param['type'] = 2;
                $param['statusType'] = '解除设备授权';
                $jPush = LogUtil::addPushLog($param);
                if(in_array(200,$jPush)){
                    return ToolUtil::returnJson(200,'解除授权成功');
                }                
                return ToolUtil::returnJson(200,'解除授权成功，推送失败');
            }
            
            return ToolUtil::returnJson(300,'解除授权失败');
        }
        return ToolUtil::returnJson(301,'该设备没有授权');
    }

    /**
     * 邀请码获取老师姓名
     * @param $param
     * @return false|string
     */
    public static function codeGetUsername($param){
        $data = BatchModel::queryLeftAdmin(['rand_code'=>$param['randCode']],['username']);
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 扫描设备进行绑定
     * @param $param
     * @return false|string
     */
    public static function bindParentSn($param){
        try {
            $admin = AdminModel::queryFirst(['id'=>$param['userId']],['id','mobile','username','sn_num','group_id','t_group_id']);

            if(empty($admin['id'])){
                return ToolUtil::returnJson(303,'账号错误');
            }

            if($admin['group_id'] !== 4){
                return ToolUtil::returnJson(304,'设备只能家长账号绑定');
            }

            $adminSn = AdminSnModel::queryFirst(['value'=>$param['snCode']],['id','type_id']);
            if(!$adminSn){
                return ToolUtil::returnJson(301,'不存在该设备信息');
            }

            if($adminSn['type_id'] !== $admin['t_group_id']){
                return ToolUtil::returnJson(301,'设备不能在这个平台绑定');
            }

            $bind = BindSnModel::queryFirst(['sn_value'=>$param['snCode']],['status']);
            if($bind && $bind['status']==1){
                return ToolUtil::returnJson(302,'存在该设备，不可重复绑定');
            }

            DB::beginTransaction();

            SettingModel::delete(['admin_id'=>$param['userId'],'sn_value'=>$param['snCode']]);
            BindSnModel::delete(['sn_value'=>$param['snCode']]);
            ParentSnModel::delete(['admin_sn_id'=>$adminSn['id']]);
            AdminSnModel::edit(['value'=>$param['snCode']],['name'=>'未设置']);

            $add_parent = ParentSnModel::add(['admin_sn_id'=>$adminSn['id'],'create_time'=>time(),'phone'=>$admin['mobile'],'admin_id'=>$param['userId']]);
            $add_bind = BindSnModel::add(['sn_value'=>$param['snCode'],'phone'=>$admin['mobile']]);

            if($add_parent > 0 && $add_bind > 0){

                $param['remark'] = '设备绑定';
                $param['title'] = 'OK';
                $param['contentType'] = 11;
                $param['status'] = 1;
                $param['batch'] = array($param['snCode']);
                $param['type'] = 2;
                $param['statusType'] = '扫描设备绑定';
                $data = [
                    'phone'=>$admin['mobile'],
                    'randCode'=>ToolUtil::randStr(),
                    'id'=>$param['userId'],
                    'member_phone'=>$admin['mobile'],
                    'member_name'=>$admin['username']
                ];
                $result = LogUtil::addPushLog($param,$data);
                if(in_array(200,$result)){
                    
                    DB::commit();
                    return ToolUtil::returnJson(200,'等待平板确定');
                    
                }else{
                    DB::rollBack();
                    return ToolUtil::returnJson(303,'推送绑定失败');
                }

            }else{

                DB::rollBack();
                return ToolUtil::returnJson(303,'绑定出错');

            }
            
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'绑定错误');
        }
    }

    /**
     * 解除设备绑定
     * @param $param
     * @return false|string
     */
    public static function relieveBindParentSn($param){
        try {
            $parentSn = ParentSnModel::queryWhereFirst(['a.value'=>$param['sn']],['p.id','p.admin_sn_id']);
            if($parentSn){
                DB::beginTransaction();
                $param['remark'] = '解除设备绑定';
                $parent = ParentSnModel::delete(['id'=>$parentSn['id']]);
                $bind = BindSnModel::delete(['sn_value'=>$param['sn']]);
                $ter = Db::table('t_teacher_sn')->where('admin_sn_id',$parentSn['admin_sn_id'])->delete();
                $admin = AdminModel::queryFirst(['id'=>$param['userId']],['sn_num']);
                if($admin['sn_num']<0){
                    $snNum = 0;
                }else{
                    $snNum = $admin['sn_num']-1;
                }
                AdminModel::edit(['id'=>$param['userId']],['sn_num'=>$snNum]);
                SettingModel::delete(['admin_id'=>$param['userId'],'sn_value'=>$param['sn']]);
                DB::table('t_app_ground')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_app_inside')->where(['sn'=>$param['sn']])->delete();
                DB::table('t_app_install')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_app_jump')->where(['sn'=>$param['sn']])->delete();
                DB::table('t_app_log')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_app_use_info')->where(['sn'=>$param['sn']])->delete();
                DB::table('t_browser')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_parent_app')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_run_app')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_screenshot')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_sn_uid')->where(['sn'=>$param['sn']])->delete();
                DB::table('t_statistics_app')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_time_control')->where(['sn_value'=>$param['sn']])->delete();
                DB::table('t_white_app')->where(['sn'=>$param['sn']])->delete();

                if($parent>0 && $bind>0){
                    $adminSn = [
                        'model'=>'',
                        'addr'=>'',
                        'imel'=>'',
                        'system'=>'',
                        'devices_version'=>'',
                        'orm_version'=>'',
                        'screen_px'=>'',
                        'quantity'=>'',
                        'device_memory'=>'',
                        'storage'=>'',
                        'cpu'=>'',
                        'name'=>'',
                        'avatar'=>'https://zuoyepad.oss-cn-beijing.aliyuncs.com/zuoyapdsetting/2.png',
                        'appstore_version'=>'',
                        'updatetools_version'=>'',
                        'info_version'=>'',
                        'jiaoguanyi_version'=>'',
                        'gankao_version'=>'',
                        'online'=>0,
                        'school'=>null,
                        'mac'=>'',
                        'is_lock'=>1,
                        'is_reset'=>0,
                        'is_wifi'=>0,
                        'start_time'=>0,
                        'end_time'=>0,
                        'minute'=>0,
                        'longitude'=>'',
                        'latitude'=>'',
                        'unbound_time'=>time(),
                        'is_screen_lock'=>0
                        ];
                    AdminSnModel::edit(['value'=>$param['sn']],$adminSn);
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$param['sn']]);
                    LogUtil::addAdminLog($param);
                    $param['title'] = 'OK';
                    $param['contentType'] = 17;
                    $param['status'] = 1;
                    $param['batch'] = array($param['sn']);
                    $param['type'] = 2;
                    $param['statusType'] = '解除设备绑定';
                    $jPush = LogUtil::addPushLog($param);
                    DB::commit();
                    if(in_array(200,$jPush)){
                        return ToolUtil::returnJson(200,'解绑成功');
                    }
                    return ToolUtil::returnJson(200,'解绑成功,推送失败');
                }
                return ToolUtil::returnJson(300,'失败');
            }
            return ToolUtil::returnJson(301,'没有该设备信息');
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵，请稍后再试');
        }
    }

    /**
     * 获取绑定是否成功
     * @param $param
     * @return false|string
     */
    public static function getFlatIsSuccess($param){
        $bind = BindSnModel::queryFirst(['sn_value'=>$param['sn']],['id','status']);
        if($bind['status']==1){
            $data = ParentSnModel::queryWhereFirst(['a.value'=>$param['sn']],['p.id','a.value']);
            return ToolUtil::returnJson(200,'绑定成功',$data);
        }
        return ToolUtil::returnJson(300,'绑定失败');
    }

    /**
     * 获取授权数据
     * @param $param
     * @return false|string
     */
    public static function getEmpower($param){
        $admin = AdminModel::queryFirst(['id'=>$param['userId']],['group_id']);
        if($admin['group_id']==3){
            $data = SendTeacherModel::queryAll(['s.teacher_id'=>$param['userId'],'s.status'=>0]);
        }elseif($admin['group_id']==4){
            $data = SendTeacherModel::queryAll(['s.parent_id'=>$param['userId'],'s.status'=>2]);
        }else{
            $data = [];
        }
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }


    /**
     * 获取sn的uid
     * @param $param
     * @return false|string
     */
    public static function getSnUid($param){

        $sn = ToolUtil::filterStr($param['sn']);
        $data = DB::table('t_sn_uid')->where('sn', $sn)->first(['id','sn','uid']);
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(300,'没有数据');
    }

}